import Vue from "vue";
import axios from "axios";
import store from "@/store";
import notification from "ant-design-vue/es/notification";
import { VueAxios } from "./axios";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import router from "../router";

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  timeout: 6000 // 请求超时时间
});

// const err = error => {
//   if (error.response) {
//     const data = error.response.data;
//     const token = Vue.ls.get(ACCESS_TOKEN);

//   return Promise.reject(error);
// };

// request interceptor
service.interceptors.request.use(config => {
  const token = localStorage.getItem('plat_token')
  if (token) {
    config.headers["Authorization"] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config;
}, err => {
  return Promise.reject(err)
});

// response interceptor
service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return response.data
    }
  },
  (error) => {
    if (error.response) {
      if (
        error.response.data &&
        (error.response.data.code === 10001 || error.response.data.code === 10000 || error.response.data.code === 10002)
      ) {
        router.push({name: 'login'})
      }
      return error.response.data
    } else if (error.request) {
      return error.request
    } else {
      return error.message
    }
  }
);

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service);
  }
};

export { installer as VueAxios, service as axios };
